<?php
class UploadDone extends Action implements IUploader {
	private $last_error = '';
	private $pwd = '';
	private $fs = false;
	/* (non-PHPdoc)
	 * @see Action::execute()
	 */
	public function execute($params) {
		PluginManager::enabled ( 'cn.usephp.filemgr');
		$me = check_login ( ADMIN_LOGIN_PAGE );
		$tmpdir = '/appdata/tmp/plupload/';
		rqrestore ( "UploadDone", false );
		$count = irqst ( 'uploader_count', 0 );
		$this->pwd = rqst ( 'cwd', '' );
		if (empty ( $this->pwd )) {
			$this->pwd = '/';
		} else {
			$this->pwd = "/{$this->pwd}/";
		}
		$data = array ('success' => true );
		if ($count > 0) {
			$this->fs = getFileSystem ();
			if (! $this->fs) {
				need_transit ( 'filesmgr', $this->url, "UploadDone" );
			}
			rqdel ( "UploadDone" );
			@set_time_limit ( 0 );
			$uploader = $this; //得到文件上传器			
			$efs = array ();
			for($i = 0; $i < $count; $i ++) {
				$tmpfile = new UploadTmpFile ( $i, $tmpdir, true );
				$rst = false;
				if ($tmpfile->isuploaded () && $uploader->allowed ( $tmpfile->file_ext )) {
					$rst = $uploader->save ( $tmpfile );
				} else {
					elog ( "文件上传失败: 文件上传不完整或文件类型不允许。" );
				}
				if ($rst === false) {
					elog ( "文件上传失败: " . $uploader->get_last_error () );
					$efs [] = $tmpfile->name;
				}
				$tmpfile->delete ();
			}
			
			if (! empty ( $efs )) {
				$cnt = count ( $efs );
				$data ['msg'] = "本次共有{$cnt}个文件未能正确上传：\n" . implode ( "\n", $efs );
			}
		}
		return new JsonView ( $data );
	}
	/**
	 * 保存
	 * @see IUploader::save()
	 */
	public function save($file) {
		$_fs = $this->fs;
		if ($_fs) {
			$tmp_file = $file->tmpname;
			$destfile = $this->pwd . $file->name;
			$result = $_fs->move ( $tmp_file, $destfile, true );
			if ($result == false) {
				$this->last_error = '无法将文件[' . $tmp_file . ']重命名为[' . $destfile . ']';
				return false;
			}
			return true;
		}
		return false;
	}
	/*
	 * (non-PHPdoc) @see IUploader::get_last_error()
	 */
	public function get_last_error() {
		return $this->last_error;
	}
	/*
	 * (non-PHPdoc) @see IUploader::getMaxSize()
	 */
	public function getMaxSize() {
		return 2097152000; // 20M
	}
	/*
	 * (non-PHPdoc) @see IUploader::getTypes()
	 */
	public function allowed($ext) {
		static $types = false;
		if (! $types) {
			$types = array ('.js', '.css', '.tpl', '.php', '.jpg', '.gif', '.png', '.bmp', '.jpeg', '.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.doc', '.docx', '.txt', '.ppt', '.pptx', '.xls', '.xlsx', '.pdf', '.mp3', '.avi', '.mp4', '.flv', '.swf' );
		}
		return in_array ( $ext, $types );
	}
}